﻿Public Class SimpleTaskScheduler
    Implements Core.Interfaces.ITaskScheduler

    Public Sub RunAsync(ByVal task As Interfaces.ITask) Implements Interfaces.ITaskScheduler.RunAsync
        Kernel.Logger.Log("TaskScheduler", TraceEventType.Information, "Running task {0} asynchronous.", task.Id)

        If task.IsAsync Then
            ' The task is implemented asynchronous so here is nothing to do.
            task.Run()
        Else
            ' The task is implemented synchronous so we have to make it async.
            Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(AddressOf RunAsyncHelper), task)
        End If
    End Sub

    ''' <summary>
    ''' This is a helper to allow asynchronous execution of a task. It casts the state object to ITask and executes the Run method.
    ''' </summary>
    Private Sub RunAsyncHelper(ByVal state As Object)
        Dim task As Interfaces.ITask

        Try
            task = DirectCast(state, Interfaces.ITask)
            task.Run()
        Catch ex As Exception
            Core.Kernel.Exceptions.PublishException(ex)
        End Try
    End Sub

    Public Sub RunSync(ByVal task As Interfaces.ITask) Implements Interfaces.ITaskScheduler.RunSync
        Kernel.Logger.Log("TaskScheduler", TraceEventType.Information, "Running task {0} synchronous.", task.Id)

        If Not task.IsAsync Then
            ' The task is implemented synchronous so here is nothing to do.
            task.Run()
        Else
            ' The task is implemented asynchronous so we have to wait for it to complete.
            task.Run()
            task.WaitCompleted()
        End If
    End Sub
End Class